﻿#if NETSTANDARD
using CRL.Core.Remoting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRL.Core.Extension;
using System.IO;
using System.Reflection;
using System.Linq.Expressions;
#endif
namespace CRL.ApiGenerate.NetCore
{

#if NETSTANDARD
    public class ApiGenerateMiddleware
    {
        private readonly RequestDelegate _next;
        ServerCreater _serverCreater;
        IServiceProvider _serviceProvider;
        public ApiGenerateMiddleware(RequestDelegate next, ServerCreater serverCreater, IServiceProvider serviceProvider)
        {
            _next = next;
            _serverCreater = serverCreater;
            _serviceProvider = serviceProvider;
            //_serverCreater.CreateApi();
        }

        public async Task Invoke(HttpContext httpContext)
        {
            var arry = httpContext.Request.Path.Value.Split('/');
            var prefix = arry[1];
            var serviceKey = $"{ServerType.ApiGenerate}.{prefix}.{(arry.Length > 2 ? arry[2] : "")}";
            if (_serverCreater.CheckServerExists(serviceKey, out var info))
            {
                await OnRequest(httpContext, prefix ,info);
                return;
            }
            await _next(httpContext);
        }

        async Task OnRequest(HttpContext context,string prefix, serviceInfo serviceInfo)
        {
            var request = context.Request;
            var response = context.Response;
            response.Headers.Add("Access-Control-Allow-Origin", "*");
            var path = request.Path.Value;
            var arry = path.Split('/');
            var service = arry[2];
            var method = arry[3];
            var headTokenName = ServerCreater.__HeadTokenName;
            var token = request.Headers[headTokenName];
            var requestMsg = new RequestJsonMessage()
            {
                Service = service,
                Method = method,
                Token = token,
                ApiPrefix = prefix
            };
            requestMsg.Args = new List<object>();
            if (request.ContentLength > 0)//仅一个参数
            {
                var reader = new StreamReader(request.Body);
                var args = await reader.ReadToEndAsync();
                requestMsg.Args.Add(args.ToObject<object>());
            }
            else//query参数
            {
                var methodInfo = serviceInfo.GetMethod(method);
                var methodParamters = methodInfo.Parameters;
                var nv = request.HttpContext.Request.Query;
                foreach (var p in methodParamters)
                {
                    object obj = null;
                    if (nv.ContainsKey(p.Name))
                    {
                        obj = nv[p.Name].ToString();
                    }
                    requestMsg.Args.Add(obj);
                }
            }
            //var instance = ServerCreater.Instance;
            var server = _serverCreater.GetServer(ServerType.ApiGenerate);
            var result = server.InvokeResult(requestMsg, type =>
             {
                 //获取注入的AbsService
                 return _serviceProvider.GetService(type);
             }) as ResponseJsonMessage;
            if (result.Success)
            {
                await response.WriteAsync(result.Data);
            }
            else
            {
                response.HttpContext.Response.StatusCode = Convert.ToInt32(result.Data);
                await response.WriteAsync(result.ToJson());
            }
        }
    }
#endif
}
